package com.study.system.search.listener;

import com.alibaba.fastjson.JSON;
import com.study.system.entity.Course;
import com.study.system.entity.ElasticsearchEntity;
import com.study.system.search.dao.ElasticsearchDAO;
import com.study.system.search.service.CourseIndexService;
import jakarta.annotation.Resource;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;

@Configuration
public class CourseMQListener {

    public static final String QUEUE_UPDATE = "course-update-queue";
    public static final String QUEUE_DELETE = "course-delete-queue";
    public static final String COURSE_EXCHANGE = "course-exchange";
    public static final String KEY_UPDATE = "course-update-key";
    public static final String KEY_DELETE = "course-delete-key";

    @Resource
    private CourseIndexService courseIndexService;

    /**
     * 监听课程添加或更新的队列
     * @param course
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = QUEUE_UPDATE,durable = "true"),
            exchange = @Exchange(value = COURSE_EXCHANGE,type = ExchangeTypes.TOPIC,ignoreDeclarationExceptions = "true"),
            key = KEY_UPDATE))
    public void listenCourseUpdate(String course){
        System.out.println("更新课程：" + course);
        Course course1 = JSON.parseObject(course, Course.class);
        try {
            courseIndexService.saveCourse(course1);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 监听课程删除队列
     * @param courseId
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = QUEUE_DELETE,durable = "true"),
            exchange = @Exchange(value = COURSE_EXCHANGE,type = ExchangeTypes.TOPIC,ignoreDeclarationExceptions = "true"),
            key = KEY_DELETE))
    public void listenCourseDelete(Long courseId){
        System.out.println("删除课程：" + courseId);
        try {
            courseIndexService.deleteCourse(courseId.intValue());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
